﻿//////////////////////////////////////////////////////////////////////////////
//
// Copyright © 1998-2024 Glodon Company Limited.
//
// Licensed under the MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the “Software”),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//////////////////////////////////////////////////////////////////////////////
#include "GbmpCreateRefPlaneByLineCmd.h"
#include "GbmpUiPlatformCommandRegister.h"
#include "GbmpUiPlatformCommandIds.h"
#include "GbmpControlIds.h"
#include "CmdStatusUtils.h"
#include "ActionDrawStraightElementInput.h"
#include "ActionDrawStraightElementCreator.h"
#include "AddGbmpDynamicPannelUtils.h"
#include "IUiView.h"
#include "IUserTransaction.h"
#include "IModelView.h"
#include "GbmpModelViewUtil.h"
#include "Coordinate3d.h"
#include "AlgorithmProject.h"
#include "ReferencePlaneUtils.h"
#include "IReferencePlane.h"
#include "IElementBasicInformation.h"
#include "IActionInputEventArgs.h"
#include "ILineEditDefinition.h"
#include "IPlane.h"
#include "UiDocumentViewUtils.h"

#include "EnableCompileWarning_The_LAST_IncludeInCpp.h"

namespace
{
    const static std::wstring s_ActionEditOffset = GBMP_TR(L"ActionEditOffset");
}

using namespace gcmp;

//////////////////////////////////////////////////////////////////////////
GbmpCreateRefPlaneCmdByLine::GbmpCreateRefPlaneCmdByLine(void) : GbmpCommandBase(ID_COM_DRAW_STRUCTURE_REFERENCEPLANE_BY_LINE)
{
}

GbmpCreateRefPlaneCmdByLine::~GbmpCreateRefPlaneCmdByLine(void)
{
}

gcmp::OwnerPtr<IAction> GbmpCreateRefPlaneCmdByLine::ExecuteCommand(const gcmp::CommandParameters& cmdParams)
{
    m_offset = 0.0;

    ActionDrawStraightElementInput actionInput;
    actionInput.CommandId = GetCommandId();
    actionInput.LineFinishedCallback = actionInput.CreateOnLineFinishedCallback(&GbmpCreateRefPlaneCmdByLine::OnLineFinished, this);
    actionInput.InputDialogCallback = actionInput.CreateDefineInputDialogCallback(&GbmpCreateRefPlaneCmdByLine::DefineInputDialog, this);
    actionInput.InputEventCallback = actionInput.CreateOnActionInputEventCallback(&GbmpCreateRefPlaneCmdByLine::OnInputDialogValueChanged, this);

    OwnerPtr<IAction> opAction = ActionDrawStraightElementCreator::Create(actionInput);

    // 开启动态面板
    AddGbmpDynamicPannelUtils::SetupReferencePlaneCreationContext(opAction.get(), ID_PAGE_GBMP_MODIFY);
    return TransferOwnership(opAction);
}
bool GbmpCreateRefPlaneCmdByLine::IsVisible() const
{
    CMD_ONLY_VISIBLE_IN_DOCUMENT_ENVIRONMENT
}
bool GbmpCreateRefPlaneCmdByLine::IsEnabled() const
{
    if(!CommandBase::IsEnabled())
        return false;
    return true;
}

ElementId GbmpCreateRefPlaneCmdByLine::OnLineFinished(gcmp::IUiView* pCurrentView, const gcmp::Vector3d& startPt, const gcmp::Vector3d& endPt,
    const gcmp::ISnap* pStartSnap, const gcmp::ISnap* pEndSnap)
{
    IDocument* pDoc = UiDocumentViewUtils::GetCurrentDocument();
    DBG_WARN_AND_RETURN_UNLESS(pDoc, ElementId::InvalidID, L"pDoc为空",L"GDMPLab",L"2024-03-30");

    DBG_WARN_AND_RETURN_UNLESS(pCurrentView, ElementId::InvalidID, L"pCurrentView为空",L"GDMPLab",L"2024-03-30");
    IModelView* pModelView = pCurrentView->GetModelView();
    DBG_WARN_AND_RETURN_UNLESS(pModelView, ElementId::InvalidID, L"pModelView为空",L"GDMPLab",L"2024-03-30");

    gcmp::Coordinate3d workPlaneCoord = GbmpModelViewUtil::GetWorkPlaneCoordinate(pModelView);
    Vector3d planeNormal = -pModelView->GetViewDirection();
    gcmp::OwnerPtr<gcmp::IPlane> opWorkPlane = gcmp::IPlane::Create(workPlaneCoord.GetOrigin(), planeNormal);
    DBG_WARN_AND_RETURN_UNLESS(opWorkPlane, ElementId::InvalidID, L"opWorkPlane为空",L"GDMPLab",L"2024-03-30");

    //将选中的空间点（pos）投影至临时水平面
    gcmp::Vector3d projectStartPt, projectEndPt;
    Vector3d pointProjectedOnLevelPlane;
    Vector2d uvParameter;
    AlgorithmProject::Project(startPt, opWorkPlane.get(), uvParameter, projectStartPt);
    AlgorithmProject::Project(endPt, opWorkPlane.get(), uvParameter, projectEndPt);

    Vector3d dirLine = projectEndPt - projectStartPt;
    Vector3d dirOffset = opWorkPlane->GetNormal() ^ dirLine;
    dirOffset.Normalize();
    projectStartPt += dirOffset * m_offset;
    projectEndPt += dirOffset * m_offset;

    OwnerPtr<IUserTransaction> ut = IUserTransaction::Create(pDoc, GBMP_TR(L"绘制参照平面"));
    DBG_WARN_AND_RETURN_UNLESS(ut != nullptr, ElementId::InvalidID, L"创建事务失败",L"GDMPLab",L"2024-03-30");

    IReferencePlane* pReferencePlane = ReferencePlaneUtils::CreateByPoints(pDoc, projectStartPt, projectEndPt, opWorkPlane->GetNormal());
    DBG_WARN_AND_RETURN_UNLESS(pReferencePlane != nullptr, ElementId::InvalidID, L"参照平面创建失败",L"GDMPLab",L"2024-03-30");
    pReferencePlane->SetReferencePlaneType(ReferencePlaneType::UserDefined);

    gcmp::IElementBasicInformation* pElementBasicInformation = pReferencePlane->GetBasicInformation();
    DBG_WARN_AND_RETURN_UNLESS(pElementBasicInformation, ElementId::InvalidID, L"pElementBasicInformation为空",L"GDMPLab",L"2024-03-30");
    pElementBasicInformation->SetName(GBMP_TR(L"参照平面"));
    ut->Commit();

    return pElementBasicInformation->GetElementId();
}

void GbmpCreateRefPlaneCmdByLine::DefineInputDialog(DefineInputDialogParams& inputItems)
{
    inputItems.title = GBMP_TR(L"偏移值：");

    OwnerPtr<ILineEditDefinition> opEditOffsetCountLineEditDefinition = ILineEditDefinition::Create(s_ActionEditOffset, GBMP_TR(L"偏移值："), LineEditInputType::InputDouble);
    DBG_WARN_AND_RETURN_VOID_UNLESS(opEditOffsetCountLineEditDefinition, L"opEditOffsetCountLineEditDefinition为空",L"GDMPLab",L"2024-03-30");
    opEditOffsetCountLineEditDefinition->SetText(StringUtil::ToWString(m_offset));
    inputItems.inputItems.push_back(TransferOwnership(opEditOffsetCountLineEditDefinition));
}

void GbmpCreateRefPlaneCmdByLine::OnInputDialogValueChanged(gcmp::IActionInputEventArgs* pArgs)
{
    DBG_WARN_AND_RETURN_VOID_UNLESS(pArgs, L"pArgs为空",L"GDMPLab",L"2024-03-30");
    const std::pair<std::wstring, gcmp::Any>& msg = pArgs->GetInputMessage();
    const std::wstring eventID = msg.first;
    gcmp::Any inputValue = msg.second;
    if (eventID == s_ActionEditOffset)
    {
        m_offset = inputValue.cast<double>();
    }
}

REGISTER_GM_COMMAND(GbmpCreateRefPlaneCmdByLine)
